<template>
  <div class="side-tree">
    <div class="item-side-tree">
      <transition name="slide-fade">
        <aside v-show="toggle" class="aside">
          <p class="a-tit">{{ title }}</p>
          <div class="title">
            <span class="m">筛选项</span>
            <div class="tool">
              <span
                title="收起"
                class="pack-up iconfont icon-shouqiliebiao"
                @click="handleToggle"
              ></span>
            </div>
          </div>
          <!-- 已选择的筛选项 -->
          <ul class="search-tips" v-show="screenArr.length > 0">
            <li v-for="(item, index) in screenArr" :key="index">
              <p>
                <span class="tip-type">{{ item.type }}：</span>
                <span class="label-txt">{{ item.name }}</span>
              </p>
              <p class="tip-txt">{{ item.label }}</p>
              <i class="close" @click="removeScreen(index)">×</i>
            </li>
          </ul>
          <!-- tree -->
          <div class="tree">
            <dl
              v-for="(item, index) in treeData"
              :key="index"
              class="tree-items"
              :class="{ 'tree-items-highlight': item.open }"
            >
              <dt class="tit">
                <el-checkbox
                  :indeterminate="indeterminateArr[index]"
                  v-model="checkAllArr[index]"
                  @change="handleCheckedAll($event, index)"
                  class="elcheckbox1"
                  >{{ item.label }}</el-checkbox
                >
                <i
                  class="tit-btn"
                  :class="{
                    'el-icon-plus': !item.open,
                    'el-icon-minus': item.open,
                  }"
                  @click="openItems(item, index)"
                ></i>
              </dt>
              <el-collapse-transition>
                <dd v-show="item.open" class="content">
                  <!-- loading -->
                  <loading2 v-if="item.loading" :emptyText="item.emptyText" />
                  <el-checkbox-group
                    v-model="checkedItemsArr[index]"
                    @change="handleCheckedChange($event, index)"
                  >
                    <div
                      v-for="(ite, index2) in item.allChildren"
                      :key="index2"
                    >
                      <div v-if="ite.key_as_string || ite.key" class="child">
                        <el-checkbox :label="`${ite.key_as_string || ite.key}`"
                          >{{ ite.key_as_string || ite.key }}（{{
                            ite.doc_count
                          }}）</el-checkbox
                        >
                      </div>
                    </div>
                  </el-checkbox-group>
                  <div class="btn-group" :class="{ two: item.isMore }">
                    <el-button
                      @click="handleScreen(item, checkedItemsArr[index], 0)"
                      class="elbtn"
                      >筛选</el-button
                    >
                    <!-- <el-button @click="handleScreen(item, checkedItemsArr[index], 1)" class="elbtn">过滤</el-button>
                    <p v-show="item.isMore" class="more"><span @click="showMore(item)">更多</span></p> -->
                  </div>
                </dd>
              </el-collapse-transition>
            </dl>
          </div>
        </aside>
      </transition>

      <!-- 折叠筛选项 -->
      <aside v-show="!toggle" class="aside-bar" @click="handleToggle">
        <span class="iconfont icon-zhankailiebiao">展开</span>
      </aside>
    </div>
  </div>
</template>
<script>
import { mapState } from "vuex";
import {
  patentData,
  paperData,
  achieveData,
  projectData,
  standardData,
} from "./sideTree.js";
export default {
  props: {
    ctNavID: {
      type: String,
    },
    paramsSq: {
      type: String,
    },
  },
  components: {},
  data() {
    return {
      title: "",
      treeData: [],
      indeterminateArr: [],
      checkAllArr: [],
      checkedItemsArr: [],
      screenArr: [],
      toggle: true,
      moreNumber: 10,
      sideTreeData: {},
      keyword: "",
    };
  },
  mounted() {
    this.init();
    this.keyword = this.searchWord;
    this.$Bus.$on("facetData", (data) => {
      this.handleFaceData(data);
    });
  },
  computed: {
    ...mapState(["searchWord", "advancedSearchWord"]),
  },
  watch: {
    $route() {
      this.init();
    },
    screenArr() {
      setTimeout(() => {
        this.$Bus.$emit("screenArr", this.screenArr);
      }, 50);
    },
    // vuex中的变化会引起该变化 除高级检索之外
    searchWord() {
      this.keyword = this.searchWord;
    },
    // vuex中的变化会引起该变化 高级检索
    advancedSearchWord() {
      this.keyword = this.advancedSearchWord;
    },
  },

  methods: {
    handleFaceData(faceData) {
      if (this.ctNavID === "paper") {
        return;
      }
      this.facetData = faceData;
      // console.log("this.treeData", this.treeData);
      // console.log("this.facetData", this.facetData);
      this.treeData.forEach((item) => {
        let data = this.facetData[item.id];
        this.$set(item, "loading", false);
        if (data) {
          this.$set(item, "isMore", data.length > this.moreNumber);
          this.$set(item, "allChildren", data.slice(0, this.moreNumber));
          this.$set(item, "_allChildren", data);
        } else {
          this.$set(item, "emptyText", "暂无数据");
        }
      });
    },
    // 初始化tree
    init() {
      switch (this.ctNavID) {
        case "patent":
          this.title = "专利检索";
          this.sideTreeData = patentData;
          break;
        case "paper":
          this.title = "论文检索";
          this.sideTreeData = paperData;
          break;
        case "achieve":
          this.title = "成果检索";
          this.sideTreeData = achieveData;
          break;
        case "project":
          this.title = "项目库";
          this.sideTreeData = projectData;
          break;
        case "standard":
          this.title = "标准检索";
          this.sideTreeData = standardData;
          break;
      }

      let data = JSON.parse(JSON.stringify(this.sideTreeData));
      let indeterminateArr = [];
      let checkAllArr = [];
      let checkedItemsArr = [];
      for (let i in data) {
        indeterminateArr.push(false);
        checkAllArr.push([]);
        checkedItemsArr.push([]);
      }
      this.indeterminateArr = indeterminateArr;
      this.checkAllArr = checkAllArr;
      this.checkedItemsArr = checkedItemsArr;
      this.screenArr = [];
      this.treeData = JSON.parse(JSON.stringify(this.sideTreeData));
    },
    //全选
    handleCheckedAll($event, index) {
      let arr = [];
      this.treeData[index].allChildren.map((item) => {
        arr.push(item.key);
      });
      this.$set(this.checkedItemsArr, index, $event ? arr : []);
      console.log(this.checkedItemsArr);
    },
    //单选
    handleCheckedChange($event, index) {
      let checkedCount = $event.length;
      let allLength = this.treeData[index].allChildren.length;
      this.$set(this.checkAllArr, index, checkedCount === allLength);
      this.$set(
        this.indeterminateArr,
        index,
        checkedCount > 0 && checkedCount < allLength
      );
      // console.log("this.indeterminateArr",this.indeterminateArr);
    },
    //点击“+”符号 展开项目
    openItems(item, index) {
      // item.open = !item.open;
      // if (this.ctNavID === "patent") {
      //   this.openItemsPatent(item, index);
      // } else if (this.ctNavID === "paper") {
      //   this.openItemsPaper(item, index);
      // } else {
      //   this.openItemsOrther(item, index);
      // }

      if (this.ctNavID === "paper") {
        this.openItemsPaper(item, index);
      } else {
        item.open = !item.open;
      }
    },
    //其他
    openItemsOrther(item, index) {
      if (item.open === false && item.allChildren.length <= 0) {
        item.open = !item.open;
        this.$set(item, "loading", true);
        this.$set(item, "emptyText", "数据加载中...");
        let data = this.facetData[item.id];
        this.$set(item, "loading", false);
        if (data) {
          this.$set(item, "isMore", data.length > this.moreNumber);
          this.$set(item, "allChildren", data.slice(0, this.moreNumber));
          this.$set(item, "_allChildren", data);
        } else {
          this.$set(item, "emptyText", "暂无数据");
        }
      } else {
        item.open = !item.open;
      }
    },
    // 文献
    openItemsPaper(item, index) {
      let id = item.id;
      let aggs = [];
      switch (id) {
        // 专利类型
        case "article_year":
          aggs = [
            {
              action: "trend_statistic.StaticTrendDataDetail",
              parameters: {
                search_type: "PUB&YEAR",
                start_year: 1000,
                end_year: 3023,
              },
            },
          ];
          break;
        case "from_publication":
          aggs = [
            {
              action: "trend_statistic.StaticTrendDataDetail",
              parameters: {
                search_type: "TOPVENUES",
                start_year: 1000,
                end_year: 3023,
              },
            },
          ];
          break;
        case "country":
          aggs = [
            {
              action: "trend_statistic.StaticTrendDataDetail",
              parameters: {
                search_type: "PUB&AUTHOR&COUNTRY",
                start_year: 1000,
                end_year: 3023,
              },
            },
          ];
          break;
        case "org":
          aggs = [
            {
              action: "trend_statistic.StaticTrendDataDetail",
              parameters: {
                search_type: "PUB&AUTHOR&ORG",
                start_year: 1000,
                end_year: 3023,
              },
            },
          ];
          break;
        case "author":
          aggs = [
            {
              action: "trend_statistic.StaticTrendDataDetail",
              parameters: {
                search_type: "TOPAUTHORS",
                start_year: 1000,
                end_year: 3023,
              },
            },
          ];
          break;
        case "keyword":
          aggs = [
            {
              action: "trend_statistic.StaticTrendDataDetail",
              parameters: {
                search_type: "2DAnalysis",
                two_d_parm: "authors.org.keyword-keywords.keyword-5",
              },
              size: 1000,
            },
          ];
          break;
        // case "article_type":
        //   aggs = [
        //     {
        //       action: "trend_statistic.StaticTrendDataDetail",
        //       parameters: {
        //         search_type: "",
        //         start_year: 1950,
        //         end_year: 2030,
        //       },
        //     },
        //   ];
        //   break;
      }
      item.open = !item.open;
      this.$set(item, "loading", true);
      this.$set(item, "emptyText", "数据加载中...");
      this.$post(this.$Url.search.commonSearch, {
        aggs: aggs,
        dbid: this.ctNavID,
        eSearch: this.keyword,
        ips: 0,
      })
        .then((res) => {
          const data = res.data.chartData;
          if (item.id === "article_year") {
            // 数组反转
            data.reverse()
          }
          this.$set(item, "loading", false);
          if (data.length) {
            this.$set(item, "isMore", data.length > this.moreNumber);
            this.$set(item, "allChildren", data.slice(0, this.moreNumber));
            this.$set(item, "_allChildren", data);
          } else {
            this.$set(item, "emptyText", "暂无数据");
          }
        })
        .catch((err) => {
          this.$set(item, "emptyText", "暂无数据");
        });
    },
    //专利
    openItemsPatent(item, index) {
      let id = item.id;
      let aggs = [];
      switch (id) {
        // 专利类型
        case "na":
          aggs = [{ field: "na" }];
          break;
        // 国家及地区
        case "nd":
          aggs = [{ field: "nd", size: 30 }];
          break;
        // 申请日
        case "apd":
          aggs = [{ field: "apd" }];
          break;
        // 公开/公告日
        case "isd":
          aggs = [{ field: "isd" }];
          break;
        // 法律状态
        case "lss":
          aggs = [{ field: "lss" }];
          break;
        // 申请人
        case "an":
          aggs = [{ field: "an", size: 100 }];
          break;
        // 标准化申请人
        case "ann":
          aggs = [{ field: "ann", size: 100 }];
          break;
        // 发明人
        case "in":
          aggs = [{ field: "in", size: 100 }];
          break;
        // IPC分类
        case "ipcm":
          aggs = [{ field: "ipcm", size: 20 }];
          break;
        // 优先权国家
        case "prir.country":
          aggs = [{ field: "prir.country" }];
          break;
        // 价值度
        case "j":
          aggs = [{ field: "j" }];
          break;
        // 数据库过滤
        case "db":
          break;
        // 被引用国家
        case "rcc":
          break;
        // 权利要求个数
        case "acc":
          aggs = [{ field: "acc" }];
          break;
        // 代理机构
        case "lrep1":
          aggs = [{ field: "agency" }];
          break;
      }

      if (
        item.open === false &&
        item.allChildren.length <= 0 &&
        aggs.length > 0
      ) {
        item.open = !item.open;
        this.$set(item, "loading", true);
        this.$set(item, "emptyText", "数据加载中...");
        this.$post(this.$Url.search.commonSearch, {
          aggs: aggs,
          dbid: this.ctNavID,
          eSearch: this.keyword,
          ips: 0,
        })
          .then((res) => {
            let data = res.data.chartData;
            if (data) {
              this.$set(item, "loading", false);
              if (id === "nd" || id === "prir.country") {
                let d = data.filter((it) => it.key !== "");
                this.$set(item, "isMore", d.length > this.moreNumber);
                this.$set(item, "allChildren", d.slice(0, this.moreNumber));
                this.$set(item, "_allChildren", d);
              } else if (id === "acc") {
                data.sort((a, b) => {
                  return a.key - b.key;
                });

                this.$set(item, "isMore", data.length > this.moreNumber);
                this.$set(item, "allChildren", data.slice(0, this.moreNumber));
                this.$set(item, "_allChildren", data);
              } else {
                let newData = [];
                data.forEach((v) => {
                  if (v.key !== "") {
                    newData.push(v);
                  }
                });

                this.$set(item, "isMore", newData.length > this.moreNumber);
                this.$set(
                  item,
                  "allChildren",
                  newData.slice(0, this.moreNumber)
                );
                this.$set(item, "_allChildren", newData);
              }
            } else {
              this.$set(item, "emptyText", "暂无数据");
            }
          })
          .catch((err) => {
            this.$set(item, "emptyText", "暂无数据");
          });
      } else {
        item.open = !item.open;
      }
    },
    // 展示更多
    showMore(item) {
      let curLength = item.allChildren.length;
      this.$set(
        item,
        "allChildren",
        item._allChildren.slice(0, curLength + this.moreNumber)
      );
      if (item.allChildren.length >= item._allChildren.length) {
        this.$set(item, "isMore", false);
      }
    },
    //筛选
    handleScreen(item, data, mode) {
      let name = item.name;
      let type = mode === 0 ? "筛选" : "过滤";
      let arr = JSON.parse(JSON.stringify(this.screenArr));
      if (data.length <= 0) {
        this.$message({
          type: "warning",
          message: `${type}不能为空！`,
          duration: 1000,
        });
        return;
      }
      for (let i in arr) {
        if (name === arr[i].name && mode === arr[i].mode) {
          arr.splice(i, 1);
          break;
        }
      }
      let obj = {
        type: type,
        name: name,
        mode: mode,
        label: data.join("|"),
        data: data,
        item: item,
      };
      arr.push(obj);
      this.screenArr = arr;
    },
    removeScreen(index) {
      this.screenArr.splice(index, 1);
      this.$set(this.checkedItemsArr, index, []);
      this.$set(this.indeterminateArr, index, false);
    },
    handleToggle() {
      this.toggle = !this.toggle;
    },
  },
};
</script>

<style lang="scss" scoped>
.side-tree {
  background-color: $color4;
  overflow-x: hidden;
  overflow-y: auto;
  height: calc(100vh - 0.7rem);
}
.aside {
  width: 240px;
  background-color: $color4;
  .a-tit {
    text-align: center;
    line-height: 50px;
    font-size: 20px;
    font-weight: bold;
    border-bottom: 1px solid $color142;
  }
  .title {
    display: flex;
    align-items: center;
    justify-content: space-between;
    height: 63px;
    padding: 0 20px;
    border-bottom: 1px solid $color142;
    .m {
      display: inline-block;
      height: 32px;
      line-height: 32px;
      font-size: 12px;
      font-weight: bold;
      color: #000;
    }
    .tool {
      display: inline-flex;
      align-items: center;
      font-size: 12px;
      color: $color30;
      cursor: pointer;
      span {
        display: inline-block;
        margin-left: 10px;
        // &:nth-of-type(1) {
        //   margin-top: -1px;
        //   font-size: 13px;
        // }
        &.el-dropdown-link {
          padding-bottom: 2px;
          font-size: 14px;
        }
        &.pack-up {
          line-height: 32px;
          text-align: right;
          font-size: 26px;
          color: $color141;
        }
        &:hover {
          color: $color141;
        }
      }
    }
  }
  .search-tips {
    list-style: none;
    padding: 10px 20px;
    margin-bottom: 10px;
    background-color: #fff;
    li {
      display: block;
      position: relative;
      padding: 5px 10px;
      border: 1px solid $color37;
      border-radius: 3px;
      margin: 5px 0;
      p {
        margin: 4px 0 0;
        font-size: 12px;
        .tip-type {
          // color: $color30;
        }
        .label-txt {
          font-weight: 700;
          color: #000;
        }
        &.tip-txt {
          word-wrap: break-word;
          word-break: break-all;
          color: $mainColor;
        }
      }
      .close {
        position: absolute;
        top: 5px;
        right: 10px;
        display: block;
        line-height: 20px;
        font-style: normal;
        font-size: 20px;
        font-weight: 900;
        color: $color30;
        cursor: pointer;
      }
    }
  }
  .tree {
    font-size: initial;
    .tree-items {
      padding: 0 20px;
      margin: 0;
      &.tree-items-highlight {
        background-color: #fff;
        border-bottom: 1px solid $color142;
        .tit {
          border-color: transparent !important;
        }
      }
      ::v-deep {
        .elcheckbox1 {
          display: inline-flex;
          align-items: center;
          justify-content: center;
          .el-checkbox__inner {
            width: 15px;
            height: 15px;
            border-color: $color141;
          }
          .el-checkbox__label {
            padding-left: 15px !important;
            font-weight: bold;
            color: $color1;
          }
        }
      }
    }
    .tit {
      position: relative;
      height: 49px;
      line-height: 49px;
      border-bottom: 1px solid $color142;
      &.tit-open {
        height: 36px;
        line-height: 36px;
      }
      .tit-btn {
        position: absolute;
        top: 50%;
        right: 4px;
        width: 20px;
        height: 20px;
        line-height: 20px;
        margin-top: -10px;
        text-align: center;
        font-size: 17px;
        color: $color5;
        cursor: pointer;
      }
    }
    .content {
      margin-left: 15px;
      // overflow: initial !important;
      .child {
        display: flex;
        align-items: center;
        min-height: 36px;
        // padding-left: 20px;
        margin-bottom: 4px;
        // overflow: hidden;
        // text-overflow: ellipsis;
        // white-space: nowrap;
        ::v-deep {
          .el-checkbox {
            display: flex;
            align-items: center;
          }
          .el-checkbox__label {
            padding-left: 10px !important;
            box-sizing: border-box;
            overflow: initial;
            text-overflow: initial;
            white-space: initial;
            color: $color1;
          }
        }
      }
      .btn-group {
        display: flex;
        align-items: center;
        justify-content: center;
        width: 100%;
        padding: 10px 0;
        margin-left: -16px;
        &.two {
          margin-left: -6px;
          .elbtn {
            margin-left: 5px !important;
            margin-right: 5px !important;
          }
        }
        .elbtn {
          width: 91px;
          height: 30px !important;
          padding: 0;
          // padding: 5px 17px;
          border: 1px solid $color141;
          border-radius: 30px;
          font-size: 12px;
          color: $mainColor;
          outline: none;
          background-color: transparent;
          cursor: pointer;
          // &:hover {
          //   border-color: $color141;
          //   color: $color141;
          // }
          &:nth-of-type(1) {
            margin-right: 10px;
          }
        }
        .more {
          display: block;
          width: 50px;
          line-height: 20px;
          margin-right: 4px;
          text-align: right;
          cursor: pointer;
          span {
            display: inline-block;
            font-size: 12px;
            &:hover {
              color: $mainColor;
            }
          }
        }
      }
    }
  }
}
.aside-bar {
  position: fixed;
  top: 0.7rem;
  left: 0;
  z-index: 2;
  display: flex;
  align-items: center;
  justify-content: center;
  width: 20px;
  height: calc(100vh - 0.7rem);
  span {
    display: block;
    font-size: 20px;
    color: $mainColor;
    cursor: pointer;
  }
  &:hover {
    background-color: rgba($color: $mainColor, $alpha: 0.3);
  }
}

// animate
.slide-fade-enter-active {
  transition: all 0.3s ease;
}
.slide-fade-leave-active {
  transition: all 0.3s ease;
}
.slide-fade-enter,
.slide-fade-leave-to {
  margin-left: -240px;
  opacity: 0;
}
</style>
